package sgsi.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import sgsi.model.comandos.LoginComando;
import sgsi.util.Constantes;
/**
 * Clase Controladora abtracta para el manejo de aciones desde el servidor, enviandas desde las capa de presentacion. <p>
 * Responde por cada pedido con un metodo de igual valor seg&uacute;n 
 * su configuraci&oacute;n extendida de la clase <code>MultiActionController</code> del framework FrameWork Spring MVC. 
 * 
 * 
 * @see MultiActionController
 * 
 *
 */
public abstract class SgsiMultiActionController extends MultiActionController {

	
	
	BindingResult errors;

	public BindingResult getErrors() {
		return errors;
	}

	public void setErrors(BindingResult errors) {
		this.errors = errors;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		if (checkUSuarioLogueado(request)) {
			return super.handleRequestInternal(request, response);
		}
		return new ModelAndView("login.html", "command", new LoginComando());
	}

	protected boolean checkUSuarioLogueado(HttpServletRequest request) {
		return request.getSession().getAttribute(Constantes.USUARIO_LOGUEADO_FLAG) != null;
	}

	@Override
	protected void bind(HttpServletRequest request, Object command) throws Exception {

		ServletRequestDataBinder binder = createBinder(request, command);
		binder.bind(request);
		if (getValidators() != null) {
			for (int i = 0; i < getValidators().length; i++) {
				if (getValidators()[i].supports(command.getClass())) {
					ValidationUtils.invokeValidator(getValidators()[i], command, binder.getBindingResult());
				}
			}
		}
		errors = binder.getBindingResult();
	}
}
